﻿
@{
    ViewBag.Title = "Mailbox";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>站内信</title>
    <link rel="shortcut icon" href="favicon.ico">
    <link href="/Assets/Hplus/css/bootstrap.min.css" rel="stylesheet" />
    <link href="/Assets/Hplus/css/font-awesome.css?v=4.4.0" rel="stylesheet">
    <link href="/Assets/Hplus/css/plugins/iCheck/custom.css" rel="stylesheet">
    <link href="/Assets/Hplus/css/animate.css" rel="stylesheet">
    <link href="/Assets/Hplus/css/style.css?v=4.1.0" rel="stylesheet">
    @*<script src="~/Assets/Scripts/jquery-1.8.2.min.js"></script>*@
    <script src="~/Assets/Scripts/jquery.signalR-2.4.3.min.js"></script>
    <!--引用自动生成的SignalR集线器(Hub)脚本.在运行的时候在浏览器的Source下可看到-->
    <script src="/signalr/hubs" type="text/javascript"></script>
</head>

<body class="gray-bg">
    <div class="wrapper wrapper-content">
        <div class="row">
            <div class="col-sm-12 animated fadeInRight">
                <div class="mail-box-header">
                    <!-- 搜索表单 -->
                    <form id="mailSearchForm" class="pull-right mail-search">
                        <div class="input-group">
                            <input type="text" class="form-control input-sm" id="mailSearchInput" placeholder="搜索邮件">
                            <div class="input-group-btn">
                                <button type="submit" class="btn btn-sm btn-primary" id="Search">
                                    搜索
                                </button>
                            </div>
                        </div>
                    </form>
                    <h2 id="mailboxTitle">收件箱 (<span id="unreadCount">0</span>)</h2>
                    <!--工具栏-->
                    <div class="mail-tools tooltip-demo m-t-md">
                        <button class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="left" title="刷新邮件列表" id="flushed"><i class="fa fa-refresh"></i> 刷新</button>
                        <button class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="标为已读" id="Read">
                            <i class="fa fa-eye"></i>
                        </button>
                        <button class="btn btn-white btn-sm" data-toggle="tooltip" data-placement="top" title="删除邮件" id="btnDelete">
                            <i class="fa fa-trash-o"></i>
                        </button>

                    </div>
                </div>
                <div class="mail-box">

                    <table class="table table-hover table-mail" id="mailTable">
                        <tbody id="mailList">
                            
                        </tbody>
                    </table>


                </div>
            </div>
        </div>
        <!--mini聊天窗口开始-->
        <div class="small-chat-box fadeInRight animated" style="display: none;">
            <div class="heading" draggable="true">
                <small class="chat-date pull-right">
                    @DateTime.Now.ToString("yyyy.M.d")
                </small>
                公司聊天群
            </div>

            <div class="content" id="ChatBox">
                <!-- 聊天内容 -->
            </div>

            <div class="form-chat">
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" id="txtSendMessage" />
                    <span class="input-group-btn">
                        <button class="btn btn-primary" type="button" id="btnSendMessage">发送</button>
                    </span>
                </div>
            </div>
        </div>
        <!--聊天悬浮窗-->
        <div id="small-chat">
            <span class="badge badge-warning pull-right" style="display: none;">0</span>
            <a class="open-small-chat" style="cursor: pointer;">
                <i class="fa fa-comments"></i>
            </a>
        </div>
        <!--mini聊天窗口结束-->
        <input type="hidden" id="hfSession" value="@ViewBag.account" />
    </div>
    <!-- 第三方插件 -->
    <script src="/Assets/Hplus/js/plugins/pace/pace.min.js"></script>

    <!-- 全局js -->
    <script src="/Assets/Hplus/js/plugins/metisMenu/jquery.metisMenu.js"></script>
    <script src="/Assets/Hplus/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
    <script src="/Assets/Hplus/js/plugins/contextMenu/jquery.contextMenu.min.js"></script>
    <script src="/Assets/Hplus/js/plugins/layer/layer.min.js"></script>


    <!-- 自定义js -->
    <script src="/Assets/Hplus/js/content.js?v=1.0.0"></script>
    <script src="/Assets/Hplus/js/hplus.js?v=4.1.0"></script>

    <!-- iCheck -->
    <script src="/Assets/Hplus/js/plugins/iCheck/icheck.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.i-checks').iCheck({
                checkboxClass: 'icheckbox_square-green',
                radioClass: 'iradio_square-green',
            });
        });
        $(function () {
            var chat = $.connection.mailboxChatHub;
            var account = $("#hfSession").val();
            var unreadCount = 0; //未读信息的数量
            var SearchWord = ""; //搜索关键字
            InitMail()
            // 接收消息的回调
            chat.client.receiveMessage = function (account, message, isOwn) {
                if (!$(".small-chat-box").is(":visible")) {
                    unreadCount++;
                    updateUnreadBadge();
                }
                showMessage(account, message, isOwn);
            };
            chat.client.RevMail = function (json) {
                $("#mailList").empty();
                InitMail();
            }
            // 自动建立连接
            $.connection.hub.start().done(function () {
                console.log("SignalR 连接已建立");
                chat.server.sendAllMail()
            });

            //点击搜索按钮
            $("#Search").click(function () {
                SearchWord = $("#mailSearchInput").val()
                $("#mailList").empty()
                InitMail()
                return false;
            })
            // 监控连接状态
            $.connection.hub.stateChanged(function (change) {
                if (change.newState === $.signalR.connectionState.disconnected) {
                    setTimeout(function () {
                        $.connection.hub.start();
                    }, 5000);
                }
            });

            // 更新未读消息徽章
            function updateUnreadBadge() {
                var badge = $("#small-chat .badge");
                badge.text(unreadCount);
                badge.toggle(unreadCount > 0);
            }

            //刷新
            $("#flushed").click(function () {
                InitMail()
            })

            // 打开聊天窗口
            $("#small-chat .open-small-chat").click(function () {
                $(".small-chat-box").toggle();
                if ($(".small-chat-box").is(":visible")) {
                    unreadCount = 0;
                    updateUnreadBadge();
                    chat.server.markAsRead();
                    var isOwn=true;
                    $.post("/Mailbox/ShowChatMessage", function (resp) {
                        $("#ChatBox").empty();
                        if (resp.code == 0) {
                            for (var item of resp.data) {
                                if (item.Account == account) {
                                    isOwn = true;
                                } else {
                                    isOwn = false;
                                }

                                showHistoryMessage(item.Account, item.Content, isOwn, item.Time)
                            } 
                        }
                    })
                }
            });
            // 发送消息
            $("#btnSendMessage").click(function () {
                sendMessage();
            });

            // 按Enter发送消息
            $("#txtSendMessage").keypress(function (e) {
                if (e.which == 13) {
                    sendMessage();
                }
            });
            //发消息
            function sendMessage() {
                if (!account) {
                    chat.server.showError("未登录用户不能发言");
                    return;
                }
                var message = $("#txtSendMessage").val().trim();
                if (message !== "") {
                    chat.server.send(account, message);
                    // 调用保存接口
                    $.post("/Mailbox/SaveChatMessage", {account:account, message: message }, function (resp) {
                        console.log(1)
                    });
                    $("#txtSendMessage").val("");
                }
            }
            //显示消息
            function showMessage(account, message, isOwn) {
                var positionClass = isOwn ? "right" : "left";
                var datetime = new Date().toLocaleTimeString();
                var html = `
<div class="${positionClass}">
    <div class="author-name">
        ${account}
        <small class="chat-date">${datetime}</small> 
    </div>
    <div class="chat-message ${isOwn ? 'active' : ''}">
        ${message}
    </div>
</div>`;
                $("#ChatBox").append(html);
                $("#ChatBox").scrollTop($("#ChatBox")[0].scrollHeight);
            }
            //显示历史消息
            function showHistoryMessage(account, message, isOwn, datetime) {
                var positionClass = isOwn ? "right" : "left";
                var html = `
<div class="${positionClass}">
    <div class="author-name">
        ${account}
        <small class="chat-date">${datetime}</small> 
    </div>
    <div class="chat-message ${isOwn ? 'active' : ''}">
        ${message}
    </div>
</div>`;
                $("#ChatBox").append(html);
                $("#ChatBox").scrollTop($("#ChatBox")[0].scrollHeight);
            }
            //通过后端接口得到所有的信箱消息
            function InitMail() {
                $.post("/Mailbox/Mail", { SearchWord }, function (resp) {
                    $("#mailList").empty()
                    var count = resp.count;
                    $("#unreadCount").text(count)
                    bindMarkAsRead()
                    bindDeleteMails()
                    for (var mail of resp.data) {
                        // 构建附件图标HTML
                        var attachmentHtml = '';
                        if (mail.Href) {
                            attachmentHtml = `<a href="${mail.Href}" target="_blank" title="查看链接">
                               <i class="fa fa-paperclip"></i>${mail.Href}
                             </a>`;
                        }
                        if (mail.IsRead == 0) {
                            $("#mailList").append(`<tr class="unread" data-mailid="${mail.Id}">
        <td class="check-mail">
            <input type="checkbox" class="i-checks" data-mailid="${mail.Id}">
        </td>
        <td class="mail-ontact"><span class="label label-danger pull-right">未读</span></td>
        <td class="mail-subject">${mail.Contents}</td>
        <td class="attachment-cell">${attachmentHtml}</td>
        <td class="text-right mail-date">${formatRelativeTime(mail.Times)}</td>
    </tr>`);
                        } else {
                            $("#mailList").append(`<tr class="read" data-mailid="${mail.Id}">
        <td class="check-mail">
            <input type="checkbox" class="i-checks" data-mailid="${mail.Id}">
        </td>
        <td class="mail-ontact"></td>
        <td class="mail-subject">${mail.Contents}</td>
        <td class="attachment-cell">${attachmentHtml}</td>
        <td class="text-right mail-date">${formatRelativeTime(mail.Times)}</td>
    </tr>`);
                        }
                    }
                })
            }
            //标记为已读
            function bindMarkAsRead() {
                $('#Read').off('click.marker').on('click.marker', function () {
                    // 获取选中的邮件ID
                    const selectedIds = $('.i-checks:checked').map(function () {
                        return $(this).data('mailid');
                    }).get();
                    if (selectedIds.length === 0) {
                        return;
                    }
                    $.post("/Mailbox/MarkAsRead", { productData: encodeURIComponent(JSON.stringify(selectedIds)) },function (resp) {
                        if (resp.code==0) {
                            // 更新前端状态
                            selectedIds.forEach(id => {
                                $(`tr[data-mailid="${id}"]`)
                                    .removeClass('unread')
                                    .addClass('read')
                                    .find('.label.label-danger').remove();
                                $(`input.i-checks[data-mailid="${id}"]`)
                                    .prop('checked', false)
                            });
                            // 局部更新未读数（避免重新加载）
                            $("#unreadCount").text(parseInt($("#unreadCount").text()) - selectedIds.length);
                        } 
                    })
                });
            }
            //逻辑删除邮件
            function bindDeleteMails() {
                $('#btnDelete').off('click.delete').on('click.delete', function () {
                    // 获取选中的邮件ID
                    const selectedIds = $('.i-checks:checked').map(function () {
                        return $(this).data('mailid');
                    }).get();

                    if (selectedIds.length === 0) {
                        layer.msg('请先选择要删除的邮件', { icon: 2 });
                        return;
                    }
                    layer.confirm('确定要删除选中邮件吗？', {
                        icon: 3,
                        title: '删除确认'
                    }, function (index) {
                        layer.close(index);
                        $.post("/Mailbox/DeleteMails", { productData: encodeURIComponent(JSON.stringify(selectedIds)) }, function (resp) {
                            if (resp.code == 0) {
                                layer.msg('删除成功', { icon: 1 });
                                // 移除已删除的邮件行
                                selectedIds.forEach(id => {
                                    $(`tr[data-mailid="${id}"]`).remove();
                                });
                                // 更新未读计数
                                $("#unreadCount").text(parseInt($("#unreadCount").text()) - selectedIds.length);
                            } else {
                                layer.msg(resp.msg || '删除失败', { icon: 2 });
                            }
                        });
                    });
                });
            }
            // 日期格式化函数
            function formatRelativeTime(jsonDate) {
                var timestamp = jsonDate.match(/\d+/)[0];
                var date = new Date(parseInt(timestamp));
                var now = new Date();
                var diff = now - date;

                var seconds = Math.floor(diff / 1000);
                var minutes = Math.floor(seconds / 60);
                var hours = Math.floor(minutes / 60);
                var days = Math.floor(hours / 24);

                if (days > 7) {
                    return date.toLocaleDateString();
                } else if (days > 1) {
                    return days + "天前";
                } else if (days === 1) {
                    return "昨天 " + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                } else if (hours >= 1) {
                    return hours + "小时前";
                } else if (minutes >= 1) {
                    return minutes + "分钟前";
                } else {
                    return "刚刚";
                }
            }
        });
    </script>
    <style>
        .chat-message {
            max-width: 70%; /* 限制最大宽度，类似微信 */
            word-wrap: break-word; /* 强制换行 */
            word-break: break-word; /* 处理长单词和URL */
            padding: 8px 12px; /* 内边距 */
            margin: 5px 0; /* 上下间距 */
            border-radius: 5px; /* 基础圆角 */
            position: relative;
            text-align: left;
            font-size: 14px;
            line-height: 1.5; /* 行高优化 */
        }
        
    </style>
</body>

</html>


